package com.jboltai.util.share;

import java.util.HashMap;
import java.util.Map;

/**
 * AI事件之间的共享数据，会放在ThreadLocal中，并在event之间共享
 */
public class AIEventThreadShareData {

    public AIEventThreadShareData() {}
    public AIEventThreadShareData(Map<String, Object> data) {
        this.data = data;
    }

    private static final ThreadLocal<AIEventThreadShareData> TL = new ThreadLocal<>();

    private Map<String, Object> data = null;

    public static AIEventThreadShareData getShareData() {
        AIEventThreadShareData threadShareData = TL.get();
        if (threadShareData == null) {
            threadShareData = new AIEventThreadShareData();
            TL.set(threadShareData);
        }

        return threadShareData;
    }

    /**
     * 设置当前线程绑定的ThreadShareData
     * @param shareData
     * @return
     */
    public static AIEventThreadShareData setShareData(AIEventThreadShareData shareData) {
        TL.set(shareData);
        return shareData;
    }


    /**
     * 向ShareData中放入数据
     * @param key
     * @param value
     */
    public static AIEventThreadShareData set(String key, Object value) {

        AIEventThreadShareData threadShareData = getShareData();
        if (threadShareData.data == null) {
            threadShareData.data = new HashMap<>();
        }
        threadShareData.data.put(key, value);
        return threadShareData;
    }



    public static final String USER_ID_KEY = "ai_event_thread_user_id";

    /**
     * 插入UserId
     * @param userId
     */
    public static void setUserId(Long userId) {
        set(USER_ID_KEY, userId);
    }

    /**
     * 获取UserId
     * @return
     */
    public static Long getUserId() {
        return get(USER_ID_KEY);
    }


    /**
     * 根据key获取数据
     * @param key
     * @return
     * @param <T>
     */
    public static <T> T get(String key) {
        AIEventThreadShareData threadShareData = getShareData();
        if (threadShareData.data == null || threadShareData.data.containsKey(key) == false) {
            return null;
        }
        return (T) threadShareData.data.get(key);
    }


    /**
     * 清除某一个key对应的数据
     * @param key
     */
    public static void remove(String key) {
        AIEventThreadShareData threadShareData = getShareData();
        if (threadShareData.data != null) {
            threadShareData.data.remove(key);
        }
    }


    /**
     * 清空所有的数据
     */
    public static void clear() {
        AIEventThreadShareData threadShareData = getShareData();
        threadShareData.data = null;
        TL.remove();
    }


}
